package com.sansi.pencilbook.controller;

import com.sansi.pencilbook.DO.ResponseDO;
import com.sansi.pencilbook.DO.Result;
import com.sansi.pencilbook.Enum.BehaviorEnum;
import com.sansi.pencilbook.Enum.RelationEnum;
import com.sansi.pencilbook.entity.*;
import com.sansi.pencilbook.service.*;
import com.sansi.pencilbook.util.MultipartFileUtil;
import com.sansi.pencilbook.util.ResponseDOUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * 功能说明: 书籍控制器
 *
 * @author lsy13
 */
@Slf4j
@RestController
@RequestMapping("/api/book")
public class BookController extends VerifyController implements BaseController {

    @Autowired
    private BookServer bookServer;

    @Autowired
    private UseBookServer useBookServer;

    @Autowired
    private CategoryServer categoryServer;

    @Autowired
    private ISBNServer isbnServer;

    @Autowired
    private UserBookServer userBookServer;

    @Autowired
    private UserServer userServer;

    @PostMapping("/v/getBookByCategory")
    public ResponseDO getBookByCategory(@RequestParam("categoryName") String categoryName) {
        Category category = (Category) categoryServer.getCategoryByName(categoryName).getData();
        if (category != null) {
            Result result = useBookServer.getBooksByCategory(category.getCategoryId());
            return getResponseDO(result);
        }else {
            return ResponseDOUtil.setResponseDO(false, "该类别不存在");
        }
    }

    @PostMapping("/v/page/getBookByCategory")
    public ResponseDO getPageBookByCategory(@RequestParam("categoryName") String categoryName,
                                            @RequestParam("pageNum") int pageNum, @RequestParam("pageSize") int pageSize) {
        Category category = (Category) categoryServer.getCategoryByName(categoryName).getData();
        if (category != null) {
            Result result = useBookServer.getBooksByCategory(category.getCategoryId(), pageNum, pageSize);
            return getResponseDO(result);
        }else {
            return ResponseDOUtil.setResponseDO(false, "该类别不存在");
        }
    }

    @PostMapping("/v/getBookByAuthor")
    public ResponseDO getBookByAuthor(@RequestParam("author") String author) {
        Result result = useBookServer.getBooksByAuthor(author);
        return getResponseDO(result);
    }

    @PostMapping("/v/page/getBookByAuthor")
    public ResponseDO getPageBookByAuthor(@RequestParam("author") String author,
                                      @RequestParam("pageNum") int pageNum, @RequestParam("pageSize") int pageSize) {
        Result result = useBookServer.getBooksByAuthor(author,pageNum,pageSize);
        return getResponseDO(result);
    }

    @PostMapping("/v/getBookByPublisher")
    public ResponseDO getBookByPublisher(@RequestParam("publisher") String publisher) {
        Result result = useBookServer.getBooksByPublisher(publisher);
        return getResponseDO(result);
    }

    @PostMapping("/v/page/getBookByPublisher")
    public ResponseDO getPageBookByPublisher(@RequestParam("publisher") String publisher,
                                        @RequestParam("pageNum") int pageNum, @RequestParam("pageSize") int pageSize) {
        Result result = useBookServer.getBooksByPublisher(publisher, pageNum, pageSize);
        return getResponseDO(result);
    }

    @PostMapping("/v/getBookByIsbn")
    public ResponseDO getBookByIsbn(@RequestParam("Isbn") String Isbn, HttpServletRequest request) {
        //TODO:获取类别Id和类别名称
        String userAccount = "";
        if (!"".equals((userAccount=getUserAccount(request)))) {
            Calendar calendar = Calendar.getInstance();
            User user = (User) userServer.getUserByAccount(userAccount).getData();
            UserBook userBook = new UserBook(user.getUserId(), Isbn, BehaviorEnum.BROWSE.getBehavior(), new SimpleDateFormat("yyyyMMddHHmm").format(calendar.getTime()));
            userBookServer.addUserBook(userBook);
        }
        Result result = useBookServer.getBookByIsbn(Isbn);
        return getResponseDO(result);
    }

    @PostMapping("/v/getBookByName")
    public ResponseDO getBookByName(@RequestParam("name") String name) {
        Result result = useBookServer.getBooksByName(name);
        return getResponseDO(result);
    }

    @PostMapping("/v/page/getBookByName")
    public ResponseDO getPageBookByName(@RequestParam("name") String name,
                                        @RequestParam("pageNum") int pageNum, @RequestParam("pageSize") int pageSize) {
        Result result = useBookServer.getBooksByName(name, pageNum, pageSize);
        return getResponseDO(result);
    }

    @PostMapping("/v/page/getPageBooksAll")
    public ResponseDO getPageBookAll(@RequestParam("pageNum") int pageNum, @RequestParam("pageSize") int pageSize) {
        Result result = useBookServer.getBooksAll(pageNum, pageSize);
        return getResponseDO(result);
    }

    @GetMapping("/v/getBooksAll")
    public ResponseDO getBooksAll() {
        log.info("获取全部书籍");
        Result result = useBookServer.getBooksAll();
        return getResponseDO(result);
    }

    @PostMapping("/a/addBook")
    public ResponseDO addBook(@RequestBody Book book, HttpServletRequest request) {
        log.info("添加书籍");
        if (checkUser(request) || checkAdmin(request)) {
            Result result = bookServer.addBook(book);
            return ResponseDOUtil.setResponseDO(result.isSuccess(), result.getData());
        }else {
            return ResponseDOUtil.setResponseDO(false, "请登录后在操作");
        }
    }

    @PostMapping("/a/modifyBook")
    public ResponseDO modifyBook(@RequestBody Book book, HttpServletRequest request) {
        if (checkAdmin(request)) {
            Result result = bookServer.modifyBook(book);
            return getResponseDO(result);
        }else {
            return ResponseDOUtil.setResponseDO(false, "请登录后在操作");
        }
    }

    @PostMapping("/a/addBooks")
    public ResponseDO addBooks(@RequestBody List<Book> books, HttpServletRequest request) {
        if (checkAdmin(request)) {
            Result result = bookServer.addBooks(books);
            return getResponseDO(result);
        }else {
            return ResponseDOUtil.setResponseDO(false, "请登录后在操作");
        }

    }

    @PostMapping("/v/getSlideshow")
    public ResponseDO getSlideshow(@RequestParam("pageSize") int pageSize) {
        log.info("获取轮播图");
        Result result = bookServer.getBooksAll();
        List<Book> books = (List<Book>) result.getData();
        List<Book> list = new ArrayList<>();
        for (int i=0;i<pageSize;i++) {
            list.add(books.get((int) (Math.random()*books.size())));
        }
        return ResponseDOUtil.setResponseDO(true, "获取成功", list);
    }

    @GetMapping("/v/getBooksByTime")
    public ResponseDO getBooksByTime() {
        log.info("获取所有新书");
        Result result = bookServer.getBooksByTime();
        return getResponseDO(result);
    }

    @PostMapping("/v/page/getPageBooksByTime")
    public ResponseDO getPageBooksByTime(@RequestParam("pageNum") int pageNum, @RequestParam("pageSize") int pageSize) {
        log.info("获取部分新书");
        Result result = bookServer.getBooksByTime(pageNum, pageSize);
        return getResponseDO(result);
    }

    @PostMapping("/u/getBooksByRelation")
    public ResponseDO getBooksByRelation(@RequestParam("relation") String relation, HttpServletRequest request) {
        String userAccount = "";
        if (!"".equals((userAccount=getUserAccount(request))) || checkAdmin(request)) {
            User user = (User) userServer.getUserByAccount(userAccount).getData();
            Result result = bookServer.getBookByRelation(user.getUserId(), RelationEnum.valueOf(relation));
            return getResponseDO(result);
        }else {
            return ResponseDOUtil.setResponseDO(false, "请登录后在操作");
        }
    }

    @PostMapping("/u/getPageBooksByRelation")
    public ResponseDO getPageBooksByRelation(@RequestParam("relation") String relation,@RequestParam("pageNum") int pageNum, @RequestParam("pageSize") int pageSize,  HttpServletRequest request) {
        String userAccount = "";
        if (!"".equals((userAccount=getUserAccount(request))) || checkAdmin(request)) {
            User user = (User) userServer.getUserByAccount(userAccount).getData();
            Result result = bookServer.getBookByRelation(user.getUserId(), RelationEnum.valueOf(relation), pageNum, pageSize);
            return getResponseDO(result);
        }else {
            return ResponseDOUtil.setResponseDO(false, "请登录后在操作");
        }
    }

    @PostMapping("/u/checkISBN")
    public ResponseDO checkISBN(@RequestParam("ISBN") String ISBN, HttpServletRequest request) {
        if (checkUser(request)) {
            return isbnServer.checkISBN(ISBN) ? ResponseDOUtil.setResponseDO(true, "ISBN有效") :
                ResponseDOUtil.setResponseDO(false, "ISBN格式不对");
        }else {
            return ResponseDOUtil.setResponseDO(false, "请登录后在操作");
        }
    }

    @PostMapping("/u/addBooksByExcel")
    public ResponseDO addBooksByExcel(@RequestParam("file") MultipartFile xlsFile) {
        try {
            File file = MultipartFileUtil.multipartFileToFile(xlsFile);
            Result result = bookServer.addBooksByExcel(file);
			MultipartFileUtil.delteTempFile(file);
            return getResponseDO(result);
        } catch (Exception e) {
            log.error(e.getMessage());
            return ResponseDOUtil.setResponseDO(false, e.getMessage());
        }
    }

    @PostMapping("/v/searchBooks")
    public ResponseDO searchBooks(@RequestParam("param") String param) {
        Result result = useBookServer.getBooksByParam(param);
        return getResponseDO(result);
    }

    private ResponseDO getResponseDO(Result result)  {
        if (result.isSuccess()) {
            if (result.getEffectRow() > 0) {
                return ResponseDOUtil.setResponseDO(result.isSuccess(), result.getData());
            }else {
                return ResponseDOUtil.setResponseDO(result.isSuccess(), result.getMsg(), result.getData());
            }
        }else {
            return ResponseDOUtil.setResponseDO(result.isSuccess(), result.getMsg());
        }
    }
}
